/*
Copyright SecureKey Technologies Inc. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package signingmgr

import (
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/core"

	"github.com/pkg/errors"
)

// SigningManager 签名管理者
type SigningManager struct {
	cryptoProvider core.CryptoSuite
}

// New 创建签名管理者
// @param cryptoProvider sdk加密包
// @return *SigningManager
// @return error
func New(cryptoProvider core.CryptoSuite) (*SigningManager, error) {
	return &SigningManager{cryptoProvider: cryptoProvider}, nil
}

// Sign 执行签名
func (mgr *SigningManager) Sign(object []byte, key core.Key) ([]byte, error) {

	if len(object) == 0 {
		return nil, errors.New("object (to sign) required")
	}

	if key == nil {
		return nil, errors.New("key (for signing) required")
	}
	// 计算hash
	digest, err := mgr.cryptoProvider.Hash(object)
	if err != nil {
		return nil, err
	}
	// 调用签名包的签名函数
	signature, err := mgr.cryptoProvider.Sign(key, digest, nil)
	if err != nil {
		return nil, err
	}
	return signature, nil
}
